有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中确定对象的类型

我有一个类(a),它包含其他类B,C,D作为变量。在任何时候,A级都会有B、C、D填充

我们如何使用streams/map来确定当前对象的类型并将其返回给调用者


共 (1) 个答案

  1. # 1 楼答案

    import java.util.Arrays;
    
    public class A {
    
        public static class B {}
        public static class C {}
        public static class D {}
        B b;
        C c;
        D d;
        
        public A(B b, C c, D d) {
            this.b = b;
            this.c = c;
            this.d = d;
        }
    
        public Class<?> getValueType() {
            A me=this;
            try {
                return Arrays.stream(this.getClass().getDeclaredFields()).filter(field->{
                    try {
                        return field.get(me)!=null;
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        return false;
                    }
                }).findAny().get().get(me).getClass();
            } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) {
                e.printStackTrace();
                return null;
            }
        }
        
        public static void main(String args[])
        {
            System.out.println(new A(new B(),null,null).getValueType());
            System.out.println(new A(null,new C(),null).getValueType());
            System.out.println(new A(null,null,new D()).getValueType());
        }
    }